import { defineStore } from 'pinia';
import { checkLogin } from '@/common/common';
import { getUserInfo } from '@/common/api/user';
import { getLastWeekVisitDataAPI } from '@/common/api/user';

export const useUserInfoStore = defineStore('userInfo', {
    state: () => ({
        userInfo: {
            id:'',
            roles: []
        },
        puid: '',
        latestUserKey: null,
        showStatisticsForm: false,//显示统计真实成交
        statisticsFormObj: null,//统计数据对象
    }),

    getters: {
    },

    actions: {
        //验证用户信息,如果没有就获取并且更新
        async checkUserInfo(){
            if(this.userInfo.id) return;
            try {
                const res = await getUserInfo();
                if(res.status === 0){
                    this.setUserInfo(res.detail);
                    uni.setStorage({
                        key: 'userInfo',
                        data: res.detail
                    })
                }
            } catch (error) {
                console.log(error)
            }
        },
        //设置用户信息
        setUserInfo(info) {
            this.userInfo = {
                ...this.userInfo,
                ...info
            }
        },
        clearUserinfo(data) {
            this.userInfo = data
        },
        setLatestUserKey(data) {
            this.latestUserKey = data;
        },
        resetUserInfo() {
            this.userInfo = {}
        },
        setPuid(id){
            this.puid = id
        },

        //验证是否填写上周数据
        async checkLastWeekVisitData() {
            if(!checkLogin()) return false;
            if(!this.userInfo.roles.includes('kfs')) return false;
            try {
                let { status, detail } = await getLastWeekVisitDataAPI();
                if(status === 0) {
                    this.setShowStatisticsForm(detail.id ? false : true);
                    this.statisticsFormObj = detail;
                }
            } catch (error) {
                this.setShowStatisticsForm(false);
                console.log(error)
            }
        },

        //设置是否显示统计真实成交
        setShowStatisticsForm(type) {
			this.showStatisticsForm = type
        },
    }
})